package Java_base;

import java.util.*;

public class Comparator {

     static class Student{
        String name;
        int age;

        public Student(String s, int a){
            name = s;
            age = a;
        }
    }

    public static void main(String[] args) {
        Set<Student> set = new HashSet<>();
        set.add(new Student("Bob", 13));
        set.add(new Student("Alice", 12));
        Vector<Student> v = new Vector();
        Iterator it = set.iterator();
        while (it.hasNext()){
            v.add((Student) it.next());
        }
        v.sort(new java.util.Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1.age == o2.age){
                    return o1.name.compareTo(o2.name);
                }
                return o2.age - o1.age;
            }
        });
        for (int i = 0; i < v.size(); i++) {
            System.out.println(v.get(i).name);
        }
        System.out.println("=====================");
        // 或者
        TreeSet<Student> set2 = new TreeSet<>(new java.util.Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                if (o1.age == o2.age){
                    return o1.name.compareTo(o2.name);
                }
                return o2.age - o1.age;
            }
        });
        set2.add(new Student("Bob", 13));
        set2.add(new Student("Alice", 12));
        it = set2.iterator();
        while (it.hasNext()){
            Student s = (Student) it.next();
            System.out.println(s.name);
        }
    }

}
